<?php
require_once ('Controller/Mobile/Common.inc.php');
require_once ('View/Result.inc.php');
require_once ('Model/GuestBookPresetMessageModel.inc.php');

final class Controller extends common {
	private $Result;
	private $Loader;
	private $Callback = NULL;
	public function __construct () {
		parent::__construct();
		$trace = debug_backtrace();
		if (isset ($trace[1])) {
			$this->Loader = $trace[1]['object'];
		}
	}

	public function execude () {
		header ('Content-Type: text/xml');
		$this->Result = new Result ();
		$this->GuestBookPresetMessageModel = new GuestBookPresetMessageModel ($this->mysql);
		$this->defaultPage ();
		print $this->Result->Create ($this->Callback);
	}

	private $GuestBookPresetMessageCount = 0;
	private $GuestBookPresetMessageitem = [];
	private $pagesize = 20;
	private $page = 0;
	private $GuestBookPresetMessageModel;
	public function defaultPage () {
		$lang = 'en-US';
		if (array_key_exists ('lang', $_REQUEST)) {
			switch ($_REQUEST['lang']) {
				case 'en-US':
				case 'zh-HK':
				case 'zh-CN':
					$lang = $_REQUEST['lang']; 
					break;
			}
		}
		$this->Result->setModulename (sprintf ('M%sF%s', $this->Loader->module, __FUNCTION__));
		$this->GuestBookPresetMessageCount = $this->GuestBookPresetMessageModel->GetGuestBookPresetMessageCount ($lang);
		if (array_key_exists ('page', $_REQUEST)) {
			if (ctype_digit ($_REQUEST['page']) && ($_REQUEST['page'] * $this->pagesize) <= $this->GuestBookPresetMessageCount) {
				$this->page = $_REQUEST['page'];
			} else {
				$this->Result->setErrorCode (1);
				return;
			}
		}
		$this->GuestBookPresetMessageitem = $this->GuestBookPresetMessageModel->GetGuestBookPresetMessageItems ($this->page * $this->pagesize, $this->pagesize, $lang);
		$this->Result->setStatus (200);
		$this->Result->setErrorCode (0);
		$this->Callback = array ($this, 'getGuestBookPresetMessageCallBack');
	}

	public function getGuestBookPresetMessageCallBack ($dom, $result) {
		$result->setAttribute ('Itemnum', $this->GuestBookPresetMessageCount);
		foreach ($this->GuestBookPresetMessageitem as $data) {
			$item = $dom->createElement ('item');
			foreach ($data as $key => $value) {
				$item->setAttribute ($key, $value);
			}
			$result->appendChild ($item);
		}
	}
}
?>
